//
//  PhotoPicker.swift
//  MyDiary2025
//
//  Created by 罗万能 on 2025/6/28.
//
import SwiftUI
import PhotosUI
import AVFoundation

struct PhotoPicker: View {
    @Binding var showingImagePicker: Bool
    let onImageSelected: (UIImage) -> Void
    let onVideoSelected: (URL) -> Void
    
    @State private var selectedItem: PhotosPickerItem? = nil
    @State private var selectedImage: UIImage?
    @State private var selectedVideoURL: URL?
    @State private var mediaType: PHAssetMediaType = .image
    
    var body: some View {
        NavigationStack {
            VStack {
                MediaTypeSelector(mediaType: $mediaType)
                
                PhotosPicker(
                    selection: $selectedItem,
                    matching: mediaType == .image ? .images : .videos,
                    photoLibrary: .shared()
                ) {
                    Text(mediaType == .image ? "从相册选择图片" : "从相册选择视频")
                        .font(.headline)
                        .foregroundColor(.white)
                        .padding()
                        .background(
                            Capsule()
                                .fill(Color("title"))
                        )
                }
                .padding()
                
                if selectedItem != nil {
                    if let image = selectedImage, mediaType == .image {
                        ImagePreview(image: image, onConfirm: {
                            onImageSelected(image)
                            showingImagePicker = false
                        })
                    } else if let url = selectedVideoURL, mediaType == .video {
                        VideoPreview(videoURL: url, onConfirm: {
                            onVideoSelected(url)
                            showingImagePicker = false
                        })
                    } else {
                        ProgressView("加载中...")
                            .padding()
                    }
                }
            }
            .navigationTitle("选择媒体")
            .toolbar {
                ToolbarItem(placement: .cancellationAction) {
                    Button("取消") {
                        showingImagePicker = false
                    }
                }
            }
            .onChange(of: selectedItem) { oldItem,newItem in
                if let item = newItem {
                    loadSelectedMedia(from: item)
                }
            }
        }
    }
    
    // 加载选中的媒体资源
    private func loadSelectedMedia(from item: PhotosPickerItem) {
        if mediaType == .image {
            item.loadTransferable(type: Data.self) { result in
                DispatchQueue.main.async {
                    switch result {
                    case .success(let data):
                        if let data = data, let uiImage = UIImage(data: data) {
                            self.selectedImage = uiImage
                        } else {
                            print("无法加载图片")
                        }
                    case .failure(let error):
                        print("加载图片失败: \(error)")
                    }
                }
            }
        } else {
            item.loadTransferable(type: Data.self) { result in
                DispatchQueue.main.async {
                    switch result {
                    case .success(let video):
                        if let video = video,((try? video.write(to: FileManager.default.urls(for: .cachesDirectory, in: .userDomainMask)[0].appending(component: "\(UUID().uuidString).mp4"))) != nil) {
                            
                            self.selectedVideoURL = FileManager.default.urls(for: .cachesDirectory, in: .userDomainMask)[0].appending(component: "\(UUID().uuidString).mp4")
                        } else {
                            print("无法加载视频")
                        }
                    case .failure(let error):
                        print("加载视频失败: \(error)")
                    }
                }
            }
        }
    }
}

// 媒体类型选择器组件
struct MediaTypeSelector: View {
    @Binding var mediaType: PHAssetMediaType
    
    var body: some View {
        HStack {
            Button("图片") {
                mediaType = .image
            }
            .fontWeight(mediaType == .image ? .bold : .regular)
            .padding()
            .background(
                mediaType == .image ? Color("title") : Color.gray.opacity(0.2)
            )
            .foregroundColor(.white)
            .cornerRadius(10)
            
            Button("视频") {
                mediaType = .video
            }
            .fontWeight(mediaType == .video ? .bold : .regular)
            .padding()
            .background(
                mediaType == .video ? Color("title") : Color.gray.opacity(0.2)
            )
            .foregroundColor(.white)
            .cornerRadius(10)
        }
        .padding()
    }
}

// 图片预览组件
struct ImagePreview: View {
    let image: UIImage
    let onConfirm: () -> Void
    
    var body: some View {
        VStack {
            Text("已选择图片")
                .font(.headline)
                .padding()
            
            Image(uiImage: image)
                .resizable()
                .aspectRatio(contentMode: .fit)
                .frame(maxHeight: 200)
                .cornerRadius(15)
                .shadow(radius: 5)
                .padding()
            
            Button("确认选择") {
                onConfirm()
            }
            .font(.headline)
            .foregroundColor(.white)
            .padding()
            .background(
                Capsule()
                    .fill(Color("title"))
            )
            .padding()
        }
        .padding()
        .background(
            RoundedRectangle(cornerRadius: 15)
                .fill(Color("back"))
                .shadow(radius: 5)
        )
    }
}

// 视频预览组件
struct VideoPreview: View {
    let videoURL: URL
    let onConfirm: () -> Void
    
    var body: some View {
        VStack {
            Text("已选择视频")
                .font(.headline)
                .padding()
            
            Image(systemName: "video.fill")
                .font(.title)
                .foregroundColor(.gray)
                .frame(width: 100, height: 100)
                .background(
                    RoundedRectangle(cornerRadius: 15)
                        .fill(Color("videoBackground"))
                        .shadow(radius: 5)
                )
                .padding()
            
            Button("确认选择") {
                onConfirm()
            }
            .font(.headline)
            .foregroundColor(.white)
            .padding()
            .background(
                Capsule()
                    .fill(Color("title"))
            )
            .padding()
        }
        .padding()
        .background(
            RoundedRectangle(cornerRadius: 15)
                .fill(Color("back"))
                .shadow(radius: 5)
        )
    }
}
//
//// 视频传输类型
//struct VideoTransferable: Transferable {
//    let url: URL
//    
//    static var transferRepresentation: some TransferRepresentation {
//        FileRepresentation(contentType: .movie) { video in
//            return video.url
//        } importing: { receivedURL, _ in
//            let directory = FileManager.default.temporaryDirectory
//            let uniqueID = UUID().uuidString
//            let fileURL = directory.appendingPathComponent("\(uniqueID).mov")
//            
//            // 如果文件已存在，先删除
//            if FileManager.default.fileExists(atPath: fileURL.path) {
//                try? FileManager.default.removeItem(at: fileURL)
//            }
//            
//            // 复制文件到临时位置
//            try FileManager.default.copyItem(at: receivedURL, to: fileURL)
//            
//            return VideoTransferable(url: fileURL)
//        }
//    }
//}

#Preview(body: {
    PhotoPicker(showingImagePicker: .constant(true)) { img in
        
    } onVideoSelected: { url in
        
    }

})
